package com.util.servlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;

public class RequestUtil {


    public static<T> T parseRequset(HttpServletRequest request, Class<T> c){

        T t=null;
        try {
            t=c.newInstance();//根据反射生成实例对象
            Method[] ms=c.getMethods();


            Map<String,String[]> map=request.getParameterMap();


            //map.entrySet（）是将map里的每一个键值对//取出来封装成一个Entry对象在存到一个Set集合里面  //Map.Entry<String[], String>的意思是一个泛型，表//示Entry里装的String[]数组和string的字符串，分别是//key和value

            for(Map.Entry<String,String[]> entry:map.entrySet()){
                String key=entry.getKey();
                String[] values=entry.getValue();
                if(values!=null&&values.length>1){
                    continue;
                }
                String v=values[0];
                key="set"+key;

                for(Method m:ms){
                    if(key.equalsIgnoreCase(m.getName())){
                        String parameterTypeName=m.getParameterTypes()[0].getName();
                        if("int".equals(parameterTypeName)||"java.lang.Integer".equals(parameterTypeName)){
                            m.invoke(t, Integer.parseInt(v));

                        }else if("float".equals(parameterTypeName)||"java.lang.Float".equals(parameterTypeName)){
                            m.invoke(t, Float.parseFloat(v));
                        }else if("double".equals(parameterTypeName)||"java.lang.Double".equals(parameterTypeName)){
                            m.invoke(t, Double.parseDouble(v));
                        }else if("long".equals(parameterTypeName)||"java.lang.Long".equals(parameterTypeName)){
                            m.invoke(t, Long.parseLong(v));
                        }else if("short".equals(parameterTypeName)||"java.lang.Short".equals(parameterTypeName)){
                            m.invoke(t, Short.parseShort(v));
                        }else if("java.lang.String".equals(parameterTypeName)){
                            m.invoke(t,v);
                        }
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }


        return t;


    }

    public static void main(String[] args) {

    }
}